<template>
  <div>
    <Row>
      <i-col span="24" class="operation_item y_query_right">
        <Input v-model.trim="tParam.tag" placeholder="标签" style="min-width: 170px;" clearable class="y_condition"></Input>
        <Input v-model.trim="tParam.employeeName" placeholder="负责人" style="min-width: 170px;" clearable class="y_condition"></Input>
        <Input v-model.trim="tParam.encodeName" placeholder="用户编号或邮箱" style="min-width: 170px;" clearable class="y_condition"></Input>
        <Button type="primary" icon="md-search" @click="search()" class="y_condition">查询</Button>
      </i-col>
    </Row>

    <br>
    <List style="border-top: 1px solid #e8eaec;border-bottom: 1px solid #e8eaec;margin-top: 1rem;margin-bottom: 1rem;">
        <list-item class="list_item" v-for="(item,index) in tData.addressBookList">
          <div style="width:100%;padding: 0 0.5rem;"  >
            <Row  type="flex" justify="space-between">
              <i-col  >
<!--                <KeyValueView title="序号" :value="index+1" ></KeyValueView>-->
                <KeyValueView title="邮箱" :value="item.virtualName"></KeyValueView>
                <KeyValueView title="历史邮件">
                  <a @click="showHistory(item.virtualName)">点击查看</a>
                </KeyValueView>
                <span @click.stop style="min-width: 10rem;">
                <Icon type="md-contact" class="list_key" />
                  <span class="list_value">负责人：
                <span >{{isNotEmpty(item.employeeId)?item.employeeName:''}}</span>
                  <span style="color:#2d8cf0;font-size: 13px;cursor: pointer" v-has=tRole.EMAIL_1_201 @click="showAssign(item)">
                    <span >{{isNotEmpty(item.employeeId)?'更改':'分配'}}</span>
                  </span>
                </span>
              </span>
                <KeyValueView title="最后邮件" >{{ $tiyBJTime(item.createtime) }}</KeyValueView>
              </i-col>

            </Row>
            <Row justify="end" style="padding: 0.5rem 0">

              <i-col flex="auto" style="text-align: left">
                <KeyValueView v-if="isNotEmpty(item.userId)" title="用户编号"  >
                  <span style="color: lightseagreen;font-weight: 500">{{item.encodeName}}</span>
                  <!--                  <a @click="showUserInfo(item.userId)">{{item.encodeName}}</a>-->
                </KeyValueView>
                <KeyValueView v-if="item.emailTags!=null && item.emailTags.length>0" title="标签" >
                  <Tag style="margin-bottom: 0.4rem;" @click.stop v-for="(tag, index) in parseTags(item.emailTags)" :color="getTagColor(index)">
                    {{tag}}
                  </Tag>
                </KeyValueView>
              </i-col>

              <i-col>
                <Button ghost size="small" type="success" @click="sendEmail(item)" style="margin-right: 0.5rem">发邮件</Button>
                <Button ghost size="small" type="primary"  @click="showEmailTags(item)" >编辑</Button>

              </i-col>

            </Row>
          </div>
        </list-item>
    </List>

    <div style="float: right;">
      <Page :total="page.total" :page-size="page.stepNumber" :current="page.currentPage" @on-change="changePage"
            @on-page-size-change="sizeChange" :page-size-opts="[20,40,60,100]"
            show-sizer show-elevator/>
    </div>

    <!-- 分配负责人 -->
    <Modal v-model="tStatus.modalAssignUser.isShow" title="选择负责人"
           :styles="{top: '20px',bottom:'20px',width:'40%',}" :scrollable=false @on-ok="assignToEmployee()" >
      <Row >
        <i-col span="4">&nbsp;</i-col>
        <i-col span="16">
          <SearchCustomerService :employee-name="employeeName" ref="employeeSearch" @choose-customer-service="chooseCustomerService"></SearchCustomerService>
        </i-col>
        <i-col span="4">&nbsp;</i-col>
      </Row>
    </Modal>

    <!-- 历史往来邮件 -->
    <Modal
      v-model="tStatus.historyEmail.isShow"
      title="历史往来邮件"
      width="65"
      :styles="{align:'center'}"
      :scrollable=true>
      <div slot="footer"></div>
      <history-email  ref="HistoryEmail"></history-email>
    </Modal>

    <!-- 再发一封邮件 -->
    <Modal
      v-model="tStatus.replayEmail.isShowing"
      title=""
      :mask-closable="false"
      :styles="{top: '20px',bottom:'20px',width:'80%'}">
      <send-email v-bind:receiveUser="tParam.email.selectedUsers" v-bind:isRefresh="false"
                  v-on:listenSendEmailEvent="sendSuccess" :is-send="false"  ref="SendEmail"></send-email>
      <div slot="footer"></div>
    </Modal>

    <!-- 用户详情 -->
    <Modal
      v-model="status.modalUserInfo.isShow"
      title="用户详情"  style="font-size:14px"
      :styles="{top: '20px',bottom:'20px',width:'50%'}"
      :scrollable=false >
      <row>
        <i-col span="4" class="tiy_key" >First Name:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.firstName}}</i-col>
        <i-col span="4" class="tiy_key">Last Name:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.lastName}}</i-col>
      </row>
      <row>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.country">国家:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.country}}</i-col>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.phone">联系电话:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.phone}}</i-col>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.email">注册邮箱:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.email}}</i-col>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.contactEmail">联系邮箱:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.contactEmail}}</i-col>

      </row>
      <row>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.facebook">Facebook:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.facebook}}</i-col>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.instagram">Instagram:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.instagram}} </i-col>
      </row>
      <row>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.source">来源:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.source}}</i-col>
        <i-col span="4" class="tiy_key" v-if="searchParams.showUserInfo.inviteCode">邀请码:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.inviteCode}}</i-col>
        <i-col span="4"  class="tiy_key" v-if="searchParams.showUserInfo.useContent">用途:</i-col>
        <i-col span="8">{{searchParams.showUserInfo.useContent}}</i-col>
      </row>
      <row>
        <i-col span="4" class="tiy_key" >推送与通知:</i-col>
        <i-col span="5"><Checkbox  v-model="searchParams.showUserInfo.isPushMessage" :disabled=true ></Checkbox>接收消息推送</i-col>
        <i-col span="5"><Checkbox  v-model="searchParams.showUserInfo.isAdEmail" :disabled=true></Checkbox>接收广告邮件</i-col>
      </row>
      <row style="font-size:14px">

        <i-col span="24" align="left">
          <Select v-model="searchParams.showUserInfo.tabList"  style="width: 15rem;margin-left: 1.5rem;margin-top: 0.5rem;" filterable multiple  placeholder="用户标签">
            <Option v-for="item in tDataUser.tabList" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
          <Button type="info" style="margin-left: 0.5rem;margin-top: 0.5rem;" @click="saveUserTab()">保存</Button>
        </i-col>
      </row>
      <row>
        <div class="modal_base_div">
          <div class="modal_base_div_title" style="margin-top: 1rem"><strong>用户备注 :</strong></div>

          <Row v-for="(userNote, index) in userNoteList" :key="index" style="padding: 0.5rem 1rem">
            <i-col span="4" class="tiy_key">{{userNote.name}} :</i-col>
            <i-col span="16">{{userNote.content}}</i-col>
            <i-col span="3">
              <a href="#" @click="removeUserNote(index)" v-has=tRole.USER_2_216>
                <Icon type="ios-close-circle" size="16" color="red"/>
              </a>
            </i-col>

          </Row>

          <div style="text-align: center">
            <Button type="info" ghost @click="noteAdd" icon="md-add" style="padding: 0px 1.5rem;margin-top: 2rem" v-has=tRole.USER_2_214>新增一条备注
            </Button>
          </div>
        </div>
      </row>
    </Modal>

    <Modal
      v-model="tStatus.modalEmailTags.isShow"
      title="编辑"
      :mask-closable="false"
      >
      <Row style="margin:1rem;">
        <i-col span="24">
          <Tag color="blue" size="large" v-show="isNotEmpty(userNo)">用户编号：{{userNo}}</Tag>
          <Button type="success" icon="md-add" style="margin-left: 0.5rem" @click="relatedUser()" >关联用户</Button>
        </i-col>
        <div slot="footer"></div>
      </Row>
      <Row style="margin:1rem;">
        <i-col span="24">
          <Select v-model="emailTagArray" style="width: 70%;" filterable multiple allow-create @on-create="" placeholder="标签">
            <Option v-for="item in tData.emailTagList" :value="item" :key="item">{{ item }}</Option>
          </Select>
          <Button type="info" style="margin-left: 0.5rem" @click="saveEmailTags()">保存标签</Button>
        </i-col>
      </Row>
    </Modal>

    <Modal
      v-model="tStatus.userNo.isShow"
      title="关联用户"
      :styles="{align:'center'}"
      :scrollable=true>
      <div slot="footer"></div>
      <div style="text-align: center;margin: 1rem">
        <p v-text="tStatus.userNo.msg" style="margin-bottom: 1rem"></p>
        <Input v-if="tStatus.userNo.isSelect" v-model="tStatus.userNo.encodeName" clearable placeholder="请输入用户编号" style="width: 250px" />
        <Select v-else v-model="tStatus.userNo.userId" placeholder="请选择用户编号" style="width:250px">
          <Option v-for="item in tStatus.userNo.encodeNameList" :value="item.id" :key="item">{{item.encodeName}}</Option>
        </Select>

        <Button type="info" style="margin-left: 0.5rem" @click="manualRelate()">关联</Button>
      </div>
    </Modal>

    <Modal
      v-model="noteModal.isShow"
      :title="noteModal.title"
      :mask-closable="false"
      @on-ok="saveNote"
      :loading="noteModal.isLoading">
      <Form :model="note"   :label-width="100" :rules="ruleNote"
            ref="noteForm"  style="margin: 1rem 0px" class="modal_newuser_form"  >
        <div class="modal_base_div" >
          <Row>
            <i-col span="22">
              <FormItem label="备注名称:" prop="name">
                <Input v-model.trim="note.name" placeholder="请输入"
                       class="form_step"></Input>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col span="22">
              <FormItem label="备注内容 : " prop="content">
                <Input type="textarea" rows=4 v-model.trim="note.content" placeholder="请输入" class="form_step" ></Input>
              </FormItem>
            </i-col>
          </Row>
        </div>
      </Form>
    </Modal>

  </div>
</template>

<script>
import tiyData from "./js/addressBook/addressBook_data";
import {webList, sendEmail,getMessageStatus} from "./js/addressBook/addressBook_fun";
import tiyDataUser from "../user/js/user/user_data";
import {deleteUserNote, saveNote, userInfo} from "../user/js/user/user_funs"
import AEmailDetail from "../email/SendEmailDetail.vue"
import SendEmail from "../email/SendEmailTemplate.vue"
import KeyValueView from "../widgets/KeyValueView";
import SearchCustomerService from "../widgets/SearchCustomerService";
import HistoryEmail from "./HistoryEmail";
import {manualRelate, relatedUser, saveTags} from "./js/emailDetail/detail_funs";
import {isNotEmpty} from "../js/commonUtils";

export default {
  data() {
    return {
      tRole:{
        EMAIL_1_103:"EMAIL-1-103",
        EMAIL_1_201:"EMAIL-1-201",
        EMAIL_2_101:"EMAIL-2-101",
        COMMON_1_100:"COMMON-1-100",
      },
      id:'',
      page: tiyData.tPage,
      tParam: tiyData.tParam,
      tData: tiyData.tData,
      tStatus: tiyData.tStatus,
      selectedIndex: 0,
      tagColor: [
        "red","green","blue","navy","maroon","purple","yellow"
      ],
      selectedAddressBook:{},
      emailTagArray:[],
      userNo:'',
      employeeName:'',

      //用户信息
      searchParams: tiyDataUser.tParams,
      status:tiyDataUser.tStatus,
      tDataUser :tiyDataUser.tData,
      userNoteList:tiyDataUser.tParams.userNoteList,
      loginTypeDict: this.$store.getters.dictionaries.loginTypeDict,
      noteModal:tiyDataUser.tStatus.noteModal,
      ruleNote: {
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        content: [
          {required: true,message: '内容不能为空', trigger: 'blur'}
        ]
      },
      activeRules:{

      },
      note:tiyDataUser.tData.note,
    }
  },
  components: {KeyValueView, AEmailDetail, SendEmail ,HistoryEmail,SearchCustomerService},
  props:{
    sysEmail:Number,
  },
  methods: {
    relatedUser() {
      relatedUser(this,tiyData, this.selectedAddressBook.virtualName,this.selectedAddressBook.id,2);
    },
    manualRelate() {
      manualRelate(this, tiyData,this.selectedAddressBook.id,2);
    },
    isNotEmpty(val) {
      return isNotEmpty(val);
    },
    saveEmailTags() {
      for (let tag of this.emailTagArray) {
        if (tag == null || tag.trim() === "") {
          this.$Message.error("不能添加空标签！")
          return;
        }
      }
      if(this.emailTagArray.length <= 0){
        this.$Modal.confirm({
          content: '<p>没有选中任何标签，将清空此用户标签，确认操作？</p>',
          onOk: () => {
            saveTags(this, tiyData,2,this.emailTagArray);
          }
        });
      } else {
        saveTags(this, tiyData,2,this.emailTagArray);
      }

    },
    parseTags(tags) {
      return this.$toJson(tags);
    },
    getTagColor(index) {
      let len = this.tagColor.length;
      return this.tagColor[index%len];
    },
    search() {
      webList(this, tiyData);
    },
    showUserInfo(userId){
      userInfo(this,tiyDataUser,userId);
    },
    noteAdd(){
      this.noteModal.isShow=true;
      this.$refs['noteForm'].resetFields();
      this.note.name='';
      this.note.content='';
      this.note.id='';
    },

    saveNote(){
      saveNote(this,tiyDataUser);
    },
    removeUserNote(index){
      deleteUserNote(this,tiyDataUser,index);
    },
    showHistory(virtualName){
      this.tStatus.historyEmail.isShow=true;
      this.$refs.HistoryEmail.queryEmailHistoryList(virtualName);
    },
    saveUserTab(){
      let self=this;
      self.$Spin.show();
      let params = {
        tabIds: self.searchParams.showUserInfo.tabList,
        type:2,
        mappingId: self.searchParams.showUserInfo.userId,
      };
      self.$apiOther.updateTabMappings(params).then(response => {
        self.$Spin.hide();
        if(response.success) {
          self.$Message.success("保存成功");
          self.search();
        }else{
          self.$Modal.error(response.errorMessage);
        }
      });
    },
    sendEmail(addressBook) {
      this.$refs.SendEmail.$data.fileList.splice(0,this.$refs.SendEmail.$data.fileList.length);
      sendEmail(this, tiyData, addressBook);
    },
    showEmailTags(addressBook){
      this.selectedAddressBook=addressBook;
      if(isNotEmpty(addressBook)){
        this.userNo=addressBook.encodeName;
      }
      this.tData.emailTagList.splice(0,this.tData.emailTagList.length);
      this.id=addressBook.id;
      this.tData.emailTagList=[...this.parseTags(addressBook.emailTags)];
      this.emailTagArray=[...this.parseTags(addressBook.emailTags)];
      this.tStatus.modalEmailTags.isShow=true;
    },
    sendSuccess(isSuccess) {
      if (isSuccess) {
        tiyData.tStatus.replayEmail.isShowing = false;
      }
    },
    changePage(page) {
      tiyData.tPage.currentPage = page;
      webList(this, tiyData);
    },
    sizeChange(page) {
      tiyData.tPage.stepNumber = page;
      webList(this, tiyData);
    },
    showAssign(addressBook){ //显示分配用户窗口
      //单条分配
      tiyData.tParam.emailStatusParam.employeeId='';
      tiyData.tParam.emailStatusParam.employeeName='';
      tiyData.tParam.emailStatusParam.emailAddressId = addressBook.id;

      if(isNotEmpty(addressBook.userId)){
        getMessageStatus(this,tiyData,addressBook.userId);
      }else {
        this.employeeName=""
      }
      this.$refs['employeeSearch'].clearSelectedEmployee();
      tiyData.tStatus.modalAssignUser.isShow = true;
    },
    chooseCustomerService(value){
      if(value!=null){
        tiyData.tParam.emailStatusParam.employeeId = value.employeeId;
        tiyData.tParam.emailStatusParam.employeeName = value.userName;
      }
    },
    assignToEmployee(){ //分配用户给指定员工
      let self = this;
      if(!tiyData.tParam.emailStatusParam.employeeId){
        this.$Message.error("请选择负责人！");
        return;
      }
      //
      self.$Spin.show();
      if(tiyData.tParam.emailStatusParam.emailAddressId!=''){
        self.$apiEmail.updateEmailAddress({
          "employeeId":tiyData.tParam.emailStatusParam.employeeId,
          "type":2,
          "id":tiyData.tParam.emailStatusParam.emailAddressId,
        }).then(function (response) {
          self.$Spin.hide();
          if (response.success) {
            self.search();
          } else {
            self.$Message.error(response.errorMessage);
          }
        });

      }else{
        let ids=[];
        self.messageSelected.forEach(email=>{
          ids.push(email.emailAddressId);
        });

        self.$apiEmail.updateContactEmailLAddressBatch({
          "employeeId":tiyData.tParam.emailStatusParam.employeeId,
          "employeeName":tiyData.tParam.emailStatusParam.employeeName,
          "ids":[...new Set(ids)],
        }).then(function (response) {
          self.$Spin.hide();
          if (response.success) {
            self.search();
          } else {
            self.$Message.error(response.errorMessage);
          }
          self.messageSelected.splice(0,self.messageSelected.length);
        });

      }

    },

  },
  created() {
    tiyData.tParam.isAll = false;
  }
}
</script>

<style lang="less" scoped>
@import  (once,optional)  "../css/base";

.list_value {
  font-size: 13px;
  color: @tiyTextDescColor;
  padding-right: 1rem;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
}

.list_item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.list_item:hover {
  background: @tiySectionColor;
}

.modal_base_div {
  width: 100%;
  text-align: left;
  margin-top: 20px;
  padding: 20px;
  border: dotted thin #d1d1d1
}

.modal_base_div_title {
  text-align: left;
  margin-bottom: 10px
}

.tiy_key {
  color: #9e9e9e;
  min-width: 90px;
  display: inline-block;
  text-align: right;
  padding-right: 0.5rem;
}
</style>
